home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2272 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  49 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Initalizing variables in a for loop
  5. Date: 16 Jan 1996 15:27:01 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4dgg45$11p2@locutus.rchland.ibm.com>
  8. References: <st95h6e9-1501962022390001@myers1-006.resnet.drexel.edu>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <st95h6e9-1501962022390001@myers1-006.resnet.drexel.edu>, st95h6e9@dunx1.ocs.drexel.edu (Luke Cassady-Dorion) writes:
  14. >When initalizing a variable in a for loop as in the example below does the
  15. >compiler free up the memory allocated to that variable after the loop
  16. >exits, thus making the variable unuseable by other parts of the function,
  17. >or its it retined??
  18. >
  19. >
  20. >   for (int i=0; i < some_value, i++)
  21.  
  22. Yes and no. :-) (don't you hate answers like that?)
  23.  
  24. In "classic" C++ the int i would be available from within the for loop 
  25. on until the end of the scope that enclosed the for loop.  That is, 
  26. this would be legal:
  27.  
  28. #include<iostream.h>
  29. int main( int argc, char* argv[] ) {
  30.     for( int i = 0 ; i < argc ; ++i )
  31.         if( argv[ i ][ 0 ] == '-' )
  32.             break;
  33.     cout << "First option is argument " << i << endl;
  34.     return 0; }
  35.  
  36. Note the use of i after the for loop.  However, the draft Ansi C++ Spec 
  37. changes the scope of an object declared in the init statement of a for 
  38. loop to be just within the for loop.  This means the example above would
  39. get an error on the i variable in the cout statement.
  40.  
  41. So far, the only compiler I know of that has implemented this is the 
  42. latest version of g++.  Look for it to come to a compiler near you soon,
  43. and break some code...
  44.  
  45.  
  46. Phil Staite, team OS/2
  47. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  48.  
  49.